package com.examine.action;

import java.sql.SQLException;

import org.expressme.webwind.ActionContext;
import org.expressme.webwind.HttpUtils;
import org.expressme.webwind.Mapping;
import org.expressme.webwind.renderer.JsonRenderer;
import org.expressme.webwind.renderer.RedirectRenderer;
import org.expressme.webwind.renderer.Renderer;
import org.expressme.webwind.renderer.TemplateRenderer;
import com.examine.dao.UserData;
import com.examine.model.User;
import com.examine.utils.JsonHelper;
import com.examine.utils.MD5Helper;
import com.google.inject.Inject;

public class Login {
	@Inject
	public  UserData userData;
	
	@Mapping("/login")
	public Renderer index()
	{
		return new TemplateRenderer("/login.htm");
	}
	
	@Mapping("/login/do")
	public Renderer doLogin() throws SQLException
	{
		String userString=HttpUtils.getStringParameter("user");
		if(userString==null || userString=="")
		{			
			return new JsonRenderer(JsonHelper.createFailedJson("User can not be null."));
		}
		
		User user=	userData.FindUser(userString);
		
		String password=HttpUtils.getStringParameter("password");
		
		if(!MD5Helper.MD5ValidateHash(String.format("%s:%s", user,password), user.getPassword()))
		{
			return new JsonRenderer(JsonHelper.createFailedJson("User or Pass is wrong."));
		}
		
		return new JsonRenderer(JsonHelper.createRedirectJson("/index"));
	}
}
